using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Net;
using System.Drawing;
using System.IO;
using System.Globalization;

namespace IGGCore
{
    /// <summary>
    /// Manager of rss feeds
    /// </summary>
    public class HeymanParser
    {

        private TextInfo myTI = new CultureInfo("en-US", false).TextInfo;


        /// <summary>
        /// Return news from a source
        /// </summary>
        public List<News> GetNews(string url, int num)
        {
            List<News> newsList = new List<News>();
            News news = new News();
            news.Provider = "Jon Heyman";

            string raw = GetAllContent(url);
            raw = raw.Substring(raw.IndexOf("<div id=\"ssItem_"));
            string link = raw.Substring(raw.IndexOf("<a href=\"") + "<a href=\"".Length);
            link = link.Substring(0, link.IndexOf(">"));
            link = link.Substring(0, link.IndexOf("\""));

            raw = raw = GetAllContent(link);
            raw = raw.Substring(raw.IndexOf("<article"));
            string title = raw.Substring(raw.IndexOf("storyHdl\">") + "storyHdl\">".Length);
            title = title.Substring(0, title.IndexOf("<"));

            raw = raw.Substring(raw.IndexOf("<time class=\"storyDate"));
            string date = raw.Substring(raw.IndexOf("datetime=\"") + "datetime=\"".Length);
            date = date.Substring(0, date.IndexOf("\""));

            raw = raw.Substring(raw.IndexOf("<div class=\"storyCopy\">"));
            raw = raw.Substring(0, raw.IndexOf("</article>"));
            raw = raw.Substring(0, raw.IndexOf("<footer>"));

            // TITLES
            news.Title = title;

            // DATE
            news.Date = date;

            // LINK
            news.Link = link;

            // CONTENT
            news.Content = raw;

            newsList.Add(news);
            return newsList;
        }

        /// <summary>
        /// Get the complete source of a specified website url
        /// </summary>
        private string GetAllContent(string url)
        {
            string transContent = null;
            StreamReader reader = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                reader = new StreamReader(request.GetResponse().GetResponseStream());
                transContent = reader.ReadToEnd();
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
            return transContent;
        }


    }
}
